# from iClouds.allSerializers import *
from django.conf import settings
from django.views import View
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from datetime import datetime
from mysqldb.models import AllinpayRobotQiniuLog
from iClouds.apiheader import has_chocode
import requests, json, time, os
import logging
from . import tasks as TASKS

# from iClouds.SDKsync import threadLock

logger = logging.getLogger(__name__)


# Create your views here.
class resSync(View):
    def get(self, request):
        print("Index: GET 方法")
        args = request.GET
        logger.info(f"[resSync] [GET] {args}")
        return HttpResponse("GET 方法")

    def post(self, request):
        print("Index: Post 方法")
        args = request.body.decode("utf-8")
        logger.info(f"[resSync] [POST] {args}")
        try:
            body = json.loads(args)
        except BaseException as err:
            logger.error(f"回调错误:{err}")
            return HttpResponse("fail")

        # 释放锁
        # rds = get_redis_connection("sysconf")
        # rds.delete("do_lipsync")
        # rds.set("Lock_lipsync", int(rds.get("Lock_lipsync")) - 1, nx=True)

        # 写库
        guid = body.get("result", {}).get("id")
        url = body.get("result", {}).get("videoUrl")
        status = body.get("result", {}).get("status")  # "COMPLETED"
        if status == "COMPLETED":
            try:
                task = AllinpayRobotQiniuLog.objects.get(description=guid)
            except BaseException as err:
                logger.warn(f"[Lipsync] 加载任务失败 {err}")
            else:
                # out = self.downloadAudio(url)
                # task.resource = (
                #     "https://lease.3vppt.com/static/" + out.split("statics")[1]
                # )
                task.resource = url
                task.status = 1
                task.lasttime = datetime.now()
                task.description = "完成"
                task.save()
                # 设置结果
                rds = TASKS.get_redis_connection("sysconf")
                rds.set(task.guid, task.resource)
                rds.expire(task.guid, 180)
                logger.info(f"[AI唇动合成] {task.id} {url}")
                # 模板消息
                TASKS.weChatModelMessages.delay(**{"task": task.id})
        else:
            logger.warn(f"[AI唇动合成] {status} {guid} ")
        return HttpResponse("success")

    @staticmethod
    def downloadAudio(url):
        # outfile = (
        #     settings.BASE_DIR.parent
        #     / f'statics/video/{time.strftime("%Y-%m-%d", time.localtime())}/{has_chocode(16,1).upper()}'
        # )
        # print(outfile)
        # if not os.path.exists(outfile):
        #     os.makedirs(outfile)
        # outfile = os.path.join(outfile, "output.mp4")
        outfile = "output.mp4"
        r = requests.get(url, stream=True)
        with open(outfile, "wb") as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
        return outfile
